﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeRenard.Core.Cryptography.Passwords
{
    /// <summary>
    /// Basic password generator.
    /// </summary>
    public sealed class PasswordGenerator : IPasswordGenerator
    {
        private const string _symbols = @"&é'(§è!çà)-|@#{[^è!{})-µù=:;,[]?./+%£*";
        private const string _lowercaseCharacters = "abcdefghijklmnopqrstuvwxyz";
        private const string _uppercaseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private const string _numbers = "123456789";

        /// <summary>
        /// Characters to use when generating a random password.
        /// </summary>
        private readonly IEnumerable<char> _characters;

        /// <summary>
        /// Creates a new <see cref="PasswordGenerator"/>.
        /// </summary>
        /// <param name="characters">The characters to be used when generating a random password.</param>
        public PasswordGenerator(IEnumerable<char> characters = null)
        {
            if (_characters == null) {
                characters = new List<char>();
                ((List<char>)characters).AddRange(_symbols.ToCharArray());
                ((List<char>)characters).AddRange(_lowercaseCharacters.ToCharArray());
                ((List<char>)characters).AddRange(_uppercaseCharacters.ToCharArray());
                ((List<char>)characters).AddRange(_numbers.ToCharArray());
            }

            _characters = characters;
        }

        /// <summary>
        /// Generate a random password with given length.
        /// </summary>
        /// <param name="length">Length.</param>
        public string Generate(int length)
        {
            var randomPassword = new StringBuilder();

            for(int i = 0; i < length; i++) {
                randomPassword.Append(GetRandomCharacter());
            }

            return randomPassword.ToString();
        }

        /// <summary>
        /// Gets a random characters.
        /// </summary>
        /// <returns>A random character.</returns>
        private char GetRandomCharacter()
        {
            var random = StaticRandom.Next(0, _characters.Count());
            return _characters.ElementAt(random);
        }
    }
}
